package cn.good.yan.sf.t5;

/**
 * 5 删除倒数节点
 *
 * @author shengren.yan
 * @create 2024-07-06
 */
public class RemoveIndeNode {

    private int value;
    public RemoveIndeNode next;

    public RemoveIndeNode(int value, RemoveIndeNode next) {
        this.value = value;
        this.next = next;
    }

    // 删除倒数节点 (快慢指针)
    // 1 2 3 4 5  删除倒数第2节点 --- 1 2 3 5
    public RemoveIndeNode removeByIndexDESC(RemoveIndeNode old, int index) {
        RemoveIndeNode head = new RemoveIndeNode(-1, old);
        RemoveIndeNode p1 = head;
        RemoveIndeNode p2 = head;
        for (int i = 0; i < index + 1; i++) {
            p2 = p2.next;
        }
        while (p2 != null) {
            p1 = p1.next;
            p2 = p2.next;
        }
        p1.next = p1.next.next;
        return head.next;
    }

    public RemoveIndeNode removeByIndexASC(RemoveIndeNode old, int index) {
        RemoveIndeNode head = new RemoveIndeNode(-1, old);
        RemoveIndeNode node = getNode(index - 1, head);
        if (node == null) {
            return old;
        }
        RemoveIndeNode next = node.next;
        if (next == null) {
            return old;
        }
        node.next = next.next;
        return head.next;
    }

    private RemoveIndeNode getNode(int index, RemoveIndeNode head) {
        int num = -1;
        for (RemoveIndeNode i = head; i != null; i = i.next, num++) {
            if (index == num) {
                return i;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        RemoveIndeNode o5 = new RemoveIndeNode(5, null);
        RemoveIndeNode o4 = new RemoveIndeNode(4, o5);
        RemoveIndeNode o3 = new RemoveIndeNode(3, o4);
        RemoveIndeNode o2 = new RemoveIndeNode(2, o3);
        RemoveIndeNode o1 = new RemoveIndeNode(1, o2);
        o1.loop();
        System.out.println("------------");
        // 方式1：
//        RemoveIndeNode r1 = o1.removeByIndexDESC(o1, 1);
//        r1.loop();
        // 方式1：
        RemoveIndeNode r2 = o1.removeByIndexASC(o1, 1);
        r2.loop();

    }

    public void loop() {
        for (RemoveIndeNode i = this; i != null; i = i.next) {
            System.out.println(i.value);
        }
    }


}
